import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 87111
 * Date: 2025-11-04
 * Time: 18:09
 */
//固定线程个数的线程池
class MyThreadPool {
    //创建阻塞队列
    private BlockingQueue<Runnable> queue = null;
    public MyThreadPool(int n) {
        //初始化阻塞队列
        queue = new ArrayBlockingQueue<>(10);
        //创建n个线程
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(() -> {
                try {
                    while(true) {
                        Runnable tmp = queue.take();
                        tmp.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
        }
    }
    //将任务放到队列中
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

}
public class Demo4 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool threadPool = new MyThreadPool(4);
        for (int i = 0; i < 1000; i++) {
            int id = i;
            threadPool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + ": " +id);
            });
        }
    }
}
